package com.shuai.utils.filter;

import cn.hutool.core.util.ObjectUtil;
import com.shuai.enums.ErrorEnum;
import com.shuai.enums.SystemEnum;
import com.shuai.exception.SystemException;
import com.shuai.service.impl.SysUserServiceImpl;
import com.shuai.utils.jwt.JwtUtils;
import com.shuai.utils.redis.RedisUtil;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 校验Token过滤器
 *
 * @author shuai
 * @since 2022
 */
@Slf4j
@Data
@Component("checkTokenFilter")
public class CheckTokenFilter extends OncePerRequestFilter {

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private SysUserServiceImpl sysUserService;

    @Resource
    private RedisUtil redisUtil;

    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
        //获取请求url
        String url = request.getRequestURI();
        log.info("==============");
        log.info(url);
        log.info("==============");
        //token验证，登录请求、验证码请求不做token验证
        if(!url.equals("/auth/login")){
            //验证码不需要token验证
            validateToken(request);
        }

        filterChain.doFilter(request,response);
    }

    //token验证
    private void validateToken(HttpServletRequest request) {
        //从头部获取token
        String token = request.getHeader("token");
        //如果从头部获取token失败，那么从参数获取
        if(StringUtils.isEmpty(token)){
            token = request.getParameter("token");
        }
        //如果没有获取到token
        if(StringUtils.isEmpty(token)){
            throw new SystemException(ErrorEnum.ERROR_TOKEN_NOT.getMsg());
        }
        //看redis里面是否有该token
        String tokenkey = "token_"+token;
        String redisToken = redisUtil.get(tokenkey);
        // 如果redis里面没有token,说明该token失效
        if(StringUtils.isEmpty(redisToken)){
            throw new SystemException(SystemEnum.TOKEN_PAST.getMsg());
        }
        if(!token.equals(redisToken)){
            throw new SystemException("token验证失败！");
        }
        //解析token
        String username = jwtUtils.getUsernameFromToken(token);
        if(StringUtils.isEmpty(username)){
            throw new SystemException(ErrorEnum.ERROR_TOKEN_INFO.getMsg());
        }
        //获取用户信息
        UserDetails details = sysUserService.loadUserByUsername(username);
        if(ObjectUtil.isNull(details)){
            throw new SystemException(ErrorEnum.ERROR_TOKEN_GET.getMsg());
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(details,null,details.getAuthorities());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        //设置到spring security上下文
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }
}
